package com.unionftech.content_login.ui.forget

import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import com.unionftech.common.base.BaseFragment
import com.unionftech.common.base.IUpdate
import com.unionftech.common.common.bean.CountryInfo
import com.unionftech.common.common.bean.PhoneRegexInfo
import com.unionftech.common.common.bean.request.SendCodeRequest
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.common.ui.UFCountryCodeSelectDialogFragment
import com.unionftech.common.utils.CheckInputUtil
import com.unionftech.common.utils.ExtentUtil
import com.unionftech.content_login.R
import com.unionftech.common.R.string
import com.unionftech.content_login.bean.request.ForgetPasswordRequest
import com.unionftech.common.common.GlobalInfoManager

class PhoneForgetPasswordFragment : BaseFragment(), IUpdate {
    private val mEtPhone: EditText by lazy { mRootView.findViewById(R.id.et_phone) }
    private val mIvClearPhone: ImageView by lazy { mRootView.findViewById(R.id.iv_clear_phone) }
    private val mLlCountryCode: LinearLayout by lazy { mRootView.findViewById(R.id.ll_country_code) }
    private val mTvCountryCode: TextView by lazy { mRootView.findViewById(R.id.tv_country_code) }
    private val mTvPhoneError: TextView by lazy { mRootView.findViewById(R.id.tv_phone_error) }
    private lateinit var mCommonFragment: ForgetPasswordCommonFragment
    private var mRequestListener: ((request: ForgetPasswordRequest) -> Unit)? = null
    private lateinit var mCountryInfo: CountryInfo
    private val mPhoneRegexMap = mutableMapOf<String, String>()
    private var mCountryCodeDialog: UFCountryCodeSelectDialogFragment? = null

    companion object {
        private const val TAG = "PhoneForgetPasswordFragment"

        @JvmStatic
        fun newInstance() = PhoneForgetPasswordFragment().apply {
            arguments = Bundle().apply {

            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {

        }
    }

    override fun inflaterContentView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_phone_forget_password, container, false)
    }

    override fun initData() {
        super.initData()
        mCommonFragment =
            ForgetPasswordCommonFragment.newInstance(ForgetPasswordCommonFragment.TYPE_REGISTER_PHONE)
        mCommonFragment.setCompleteListener {
            mEtPhone.clearFocus()
            if (checkInput() && it) {
                requestResetPwd()
            }
        }
    }

    override fun initLanguageText() {
        super.initLanguageText()
        mEtPhone.hint = DynamicResourceManager.getString(mContext, string.phone)
    }

    override fun setListener() {
        super.setListener()
        mLlCountryCode.setOnClickListener(this)
        mIvClearPhone.setOnClickListener(this)
        mCommonFragment.setGetParentValueListener {
            if (checkInput()) {
                if (::mCountryInfo.isInitialized) {
                    return@setGetParentValueListener SendCodeRequest(
                        loginPhone = mEtPhone.text.toString(),
                        areaCode = mCountryInfo.areaCode,
                        areaCountry = mCountryInfo.code,
                        check = true,
                        isContact = false,
                        businessType = 2
                    )
                }
            }
            return@setGetParentValueListener null
        }
        mEtPhone.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                //去除错误边框展示
                mEtPhone.isSelected = false
                setClearPhone(mEtPhone.text)
            } else {
                mIvClearPhone.visibility = View.GONE
                checkInput()
            }
        }
        mEtPhone.addTextChangedListener { text ->
            setClearPhone(text)
            val enable = !TextUtils.isEmpty(text)
            val result = mCommonFragment.getInputEnable() && enable
            mCommonFragment.setConfirmEnable(result)
        }
        mCommonFragment.setInputChangeCallBack {
            val result = mCommonFragment.getInputEnable() && !TextUtils.isEmpty(mEtPhone.text)
            mCommonFragment.setConfirmEnable(result)
        }
    }

    private fun setClearPhone(text: Editable?) {
        if (!TextUtils.isEmpty(text)) {
            mIvClearPhone.visibility = View.VISIBLE
        } else {
            mIvClearPhone.visibility = View.GONE
        }
    }

    private fun checkInput(): Boolean {
        val areaCode = mTvCountryCode.text.toString()
        return CheckInputUtil.checkPhoneInput(
            mEtPhone.text.toString(),
            areaCode,
            mPhoneRegexMap[areaCode] ?: "",
            mEtPhone,
            mTvPhoneError,
            string.phone_empty,
            string.phone_format_incorrect
        )
    }

    override fun setView() {
        super.setView()
        hideTitleBar()
        mRootView.setBackgroundColor(mContext.getColor(android.R.color.transparent))
        val beginTransaction = childFragmentManager.beginTransaction()
        beginTransaction.add(R.id.fl_forget_common, mCommonFragment)
        beginTransaction.commitNowAllowingStateLoss()
        childFragmentManager.executePendingTransactions()
        loadData()
    }

    override fun loadData() {
        super.loadData()
        updateAllPhoneRegex()
    }

    private fun updateAllPhoneRegex() {
        val list = GlobalInfoManager.getInstance().getAllPhoneRegex()
        if (list.isNotEmpty()) {
            mPhoneRegexMap.clear()
            for (info in list) {
                mPhoneRegexMap[info.areaCode] = info.regex
            }
        } else {
            GlobalInfoManager.getInstance().addListener(this)
            GlobalInfoManager.getInstance().update(GlobalInfoManager.UPDATE_ALL_PHONE_REGEX)
        }
    }

    fun setCountryInfo(countryInfo: CountryInfo) {
        mCountryInfo = countryInfo
        mTvCountryCode.text = mCountryInfo.areaCode
    }

    fun getCountryInfo(): CountryInfo {
        return mCountryInfo
    }

    fun setRequestListener(listener: (request: ForgetPasswordRequest) -> Unit) {
        this.mRequestListener = listener
    }

    private fun requestResetPwd() {
        if (::mCountryInfo.isInitialized) {
            val request = mCommonFragment.getResetRequestInfo().copy(
                loginPhone = mEtPhone.text.toString(),
                areaCode = mTvCountryCode.text.toString(),
                areaCountry = mCountryInfo.code
            )
            mRequestListener?.invoke(request)
        }
    }

    private fun showSelectCountryDialog() {
        if (mCountryCodeDialog == null) {
            mCountryCodeDialog = UFCountryCodeSelectDialogFragment.newInstance(mContext)
            mCountryCodeDialog!!.setCallBack { countryInfo ->
                countryInfo.also {
                    mTvCountryCode.text = it.areaCode
                    mCountryInfo = it
                    ExtentUtil.setPhoneDynamicPaddingLeft(mContext, mEtPhone, it.areaCode)
                }
            }
        }
        if (mCountryCodeDialog!!.dialog == null || !mCountryCodeDialog!!.dialog!!.isShowing) {
            mCountryCodeDialog?.show(
                childFragmentManager, UFCountryCodeSelectDialogFragment::class.java.simpleName
            )
        }
    }

    override fun doClick(v: View?) {
        when (v?.id) {
            R.id.ll_country_code -> showSelectCountryDialog()
            R.id.iv_clear_phone -> mEtPhone.setText("")
        }
    }

    fun resetData() {
        mTvCountryCode.text = mCountryInfo.areaCode
        mEtPhone.setText("")
        mCommonFragment.resetData()
    }

    override fun onUpdate(obj: Any?) {
        if (obj is List<*>) {
            updatePhoneRegex(obj)
        }
    }

    private fun updatePhoneRegex(list: List<*>) {
        mPhoneRegexMap.clear()
        for (info in list) {
            if (info is PhoneRegexInfo) {
                mPhoneRegexMap[info.areaCode] = info.regex
            }
        }
    }

    override fun onDestroy() {
        mCountryCodeDialog?.dismiss()
        mCountryCodeDialog?.setCallBack(null)
        mCountryCodeDialog = null
        GlobalInfoManager.getInstance().remove(this)
        super.onDestroy()
    }
}